﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using Microsoft.Phone.Tasks;

namespace WidgetLibrary
{
    /// <summary>
    /// Downloader class
    /// </summary>
    public class Downloader
    {
        private Uri _uri = null;
        private string _url = null;
        private IsolatedStorageFile _store = null;
        private string _baseDir;
        private string _fileName;
        private TypeFileEnum _extension;

       
        /// <summary>
        /// Constructor of Downloader
        /// </summary>
        /// <param name="url">url that contains the file to download</param>
        public Downloader(string url)
        {
            this._url = url;
            this._uri = new Uri(url, UriKind.RelativeOrAbsolute);
            this._store = IsolatedStorageFile.GetUserStoreForApplication();
            if (!_store.DirectoryExists("DownloadFiles"))
                _store.CreateDirectory("DownloadFiles");
            this._baseDir = "DownloadFiles";
            this._fileName = Helper.GetFileName(url);
            this._extension = Helper.GetFileExtension(url);
        }

        /// <summary>
        /// Download the file specified in url passed in constructor.
        /// Download the file asynchronously.
        /// </summary>
        public void Download()
        {
            WebClient wc = new WebClient();
            wc.OpenReadAsync(_uri);
            wc.OpenReadCompleted += wc_OpenReadCompleted;
        }

        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (this._extension == TypeFileEnum.IMAGE)
            {
                MediaLibrary lib = new MediaLibrary();
                lib.SavePicture(this._fileName + "." + this._extension.ToString(), e.Result);
                MessageBox.Show(this._fileName + "." + this._extension.ToString() + " was saved succesfully");
            }
            else
            {
                WebBrowserTask wbt = new WebBrowserTask();
                wbt.URL = this._url;
                wbt.Show();
            }
                
        }  


    }
}
